package com.qianxun.api;

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.qianxun.api.bo.Result;
import com.qianxun.api.error.ResultAdaptException;
import com.qianxun.framework.util.GsonFormatBuilder;
import com.qianxun.framework.util.ObjectUtil;
import com.qianxun.framework.util.http.HttpResponse;

/**
 * @author: huwei
 * @date: 2020/11/2 15:52
 * @version: 1.0.0
 */
public interface ResultAdapter {

    /**
     * 结果适配
     * @param response
     * @param resultClass
     * @return
     * @throws ResultAdaptException
     */
    default Object adapt(HttpResponse response ,Class<?> resultClass) throws ResultAdaptException{
        if (void.class.isAssignableFrom(resultClass)) {
            return null;
        }
        if (HttpResponse.class.isAssignableFrom(resultClass)) {
            return response;
        }
        if (String.class.isAssignableFrom(resultClass) || resultClass.getName().equals(Object.class.getName())) {
            return response.toString();
        }
        if (Byte[].class.isAssignableFrom(resultClass) || byte[].class.isAssignableFrom(resultClass)) {
            return response.getResponse();
        }
        if (boolean.class.isAssignableFrom(resultClass) || Boolean.class.isAssignableFrom(resultClass)) {
            return Boolean.valueOf(response.toString());
        }
        if (Result.class.isAssignableFrom(resultClass)) {
            Object res = ObjectUtil.toBean(response.getResponse(), Result.class);
            if (!ObjectUtil.isNull(res)) {
                return res;
            }
        }
        //其他结果，进行适配
        Object obj = ObjectUtil.toBean(response.getResponse(), resultClass);
        if (!ObjectUtil.isNull(obj)) {
            return obj;
        } else {
            // 预计目标请求结果为json字符串，且目标数据包含在data字段中
            try {
                JsonElement dataJsonElement = JsonParser.parseString(response.toString()).getAsJsonObject().get("data");
                String dataJson = GsonFormatBuilder.defaultFormatGson().toJson(dataJsonElement);
                obj = ObjectUtil.toBean(dataJson, resultClass);
                if (!ObjectUtil.isNull(obj)) {
                    return obj;
                }
            } catch (Throwable e) {
                //转换失败，不做处理
            }
        }
        //适配失败
        throw new ResultAdaptException(resultClass, response.toString(), "结果不匹配");
    }
}
